package com.haitaoit.chengquan.main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.base.QBaseActivity;
import com.haitaoit.chengquan.module.car.CarFragment;
import com.haitaoit.chengquan.module.car.SeverFragment;
import com.haitaoit.chengquan.module.center.CenterFragment;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.home.HomeFragment;
import com.haitaoit.chengquan.module.login.Model.LoginInfo;
import com.haitaoit.chengquan.module.near.NearFragment;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.leakcanary.RefWatcher;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by 赵航 on 2017/11/28.
 */

public class MianButtonActivity extends QBaseActivity implements View.OnClickListener {

    private static final int MIANLOGIN = 1212;
    private LayoutInflater mLayoutInflater;
    private LinearLayout   mHomeButton;
    private LinearLayout   mNearButton;
    private RelativeLayout mThreedButton;
    private LinearLayout   mMianButton;
    private FrameLayout    mFrameLayout;
    private ImageView      mHomeImage;
    private ImageView      mNearImage;
    private ImageView      mShoppingImage;
    private ImageView      mOrderImage;
    private ImageView      mMianImage;
    private LinearLayout   mShoppingLinear;
    private LinearLayout   mOrderLinear;
    private TextView       mHomeText;
    private TextView       mNearText;
    private TextView       mShoppingText;
    private TextView       mOrderText;
    private TextView       mMianText;
    private long           exitTime = 0;
    private List<Fragment> mList    = new ArrayList<>();

    @Override
    public int getContentView() {
        return R.layout.mianbuttonactivity;
    }

    @Override
    public void initView() {
        //先引入布局
        mLayoutInflater = LayoutInflater.from(this);
        HomeFragment mHomeFragment = new HomeFragment();
        NearFragment mNearFragment = new NearFragment();
        CarFragment mCarFragment = new CarFragment();
        SeverFragment mSeverFragment = new SeverFragment();
        CenterFragment mCenterFragment = new CenterFragment();
        mList.add(mHomeFragment);
        mList.add(mNearFragment);
        mList.add(mCarFragment);
        mList.add(mSeverFragment);
        mList.add(mCenterFragment);

        mFrameLayout = (FrameLayout) findViewById(R.id.framelayout);
        mHomeButton = (LinearLayout) findViewById(R.id.home_linear);
        mNearButton = (LinearLayout) findViewById(R.id.near_linear);
        mThreedButton = (RelativeLayout) findViewById(R.id.threed_button);
        mMianButton = (LinearLayout) findViewById(R.id.mian_linear);

        //五个ImageView 图片
        mHomeImage = (ImageView) findViewById(R.id.home_image);
        mNearImage = (ImageView) findViewById(R.id.near_image);
        mShoppingImage = (ImageView) findViewById(R.id.shopping_image);
        mOrderImage = (ImageView) findViewById(R.id.order_image);
        mMianImage = (ImageView) findViewById(R.id.mian_image);

        //五个文字
        mHomeText = (TextView) findViewById(R.id.home_text);
        mNearText = (TextView) findViewById(R.id.near_text);
        mShoppingText = (TextView) findViewById(R.id.shopping_text);
        mOrderText = (TextView) findViewById(R.id.order_text);
        mMianText = (TextView) findViewById(R.id.mian_text);


        //两个切换的可见的布局
        mShoppingLinear = (LinearLayout) findViewById(R.id.shopping_linear);
        mOrderLinear = (LinearLayout) findViewById(R.id.order_linear);


        mHomeButton.setOnClickListener(this);
        mNearButton.setOnClickListener(this);
        mThreedButton.setOnClickListener(this);
        mMianButton.setOnClickListener(this);
        login();
    }

    private void login() {
//        PermissionGen.with(this)
//                .addRequestCode(MIANLOGIN)
//                .permissions(
//                        Manifest.permission.CAMERA,
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_EXTERNAL_STORAGE,
//                        Manifest.permission.READ_PHONE_STATE,
//                        Manifest.permission.SEND_SMS
//                )
//                .request();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(MianButtonActivity.this, requestCode, permissions, grantResults);

    }

    @PermissionSuccess(requestCode = MIANLOGIN)
    public void requestPhotoSuccess() {
        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String equipment = TelephonyMgr.getDeviceId();
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("phone", PreferenceUtils.getPrefString("username", "")));
        list.add(new NameValuePairSign("password", PreferenceUtils.getPrefString("password", "")));
        list.add(new NameValuePairSign("equipment", equipment));
        list.add(new NameValuePairSign("registration_id", ExitApplication.getInstance().getJPushId()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("phone", PreferenceUtils.getPrefString("username", ""));
        params.addQueryStringParameter("password", PreferenceUtils.getPrefString("password", ""));
        params.addQueryStringParameter("equipment", equipment);
        params.addQueryStringParameter("registration_id", ExitApplication.getInstance().getJPushId());
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(MianButtonActivity.this, false, Constant.GetUserlogin, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败

                            return;
                        case 0:// 成功
                            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                                    .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                            LoginInfo loginInfo = gson.fromJson(Response, LoginInfo.class);
                            PreferenceUtils.setPrefString("user_id", loginInfo.getUser_id());
                            // 账号的类别
                            PreferenceUtils.setPrefString("account_type", loginInfo.getType());
                           // httpGetUserInfo(Constant.Getgr_user_model);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
            }
        });
    }

    @PermissionFail(requestCode = MIANLOGIN)
    public void requestPhotoFail() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        //        Uri uri = Uri.fromParts("package", context.getPackageName());
        //        intent.setData(uri);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);

    }

    @Override
    public void initData() {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.framelayout, mList.get(0));
        transaction.show(mList.get(0));
        transaction.commit();

        mHomeImage.setSelected(true);
        mHomeText.setTextColor(getResources().getColor(R.color.app_color));

        mNearImage.setSelected(false);
        mNearText.setTextColor(getResources().getColor(R.color.app_color_qian));

        mShoppingImage.setSelected(false);
        mShoppingText.setTextColor(getResources().getColor(R.color.app_color_qian));

        mOrderImage.setSelected(false);
        mOrderText.setTextColor(getResources().getColor(R.color.app_color_qian));

        mMianImage.setSelected(false);
        mMianText.setTextColor(getResources().getColor(R.color.app_color_qian));

    }

    @Override
    public void initEvent() {

    }

    @Override
    protected void updateUI(Message msg) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(PreferenceUtils.getPrefString("account_type", "")) || TextUtils.equals("1", PreferenceUtils.getPrefString("account_type", ""))) {
            mShoppingLinear.setVisibility(View.VISIBLE);
            mOrderLinear.setVisibility(View.GONE);
        } else {
            mShoppingLinear.setVisibility(View.GONE);
            mOrderLinear.setVisibility(View.VISIBLE);
        }
        String index = getIntent().getStringExtra("index");
        if (index!=null){
            if (3>=Integer.parseInt(index)||Integer.parseInt(index)>= 0){
                onCrureectToFragment(Integer.parseInt(index));
            }
        }
    }

    @Override
    public void onClick(View v) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.hide(mList.get(0));
        transaction.hide(mList.get(1));
        transaction.hide(mList.get(2));
        transaction.hide(mList.get(3));
        transaction.hide(mList.get(4));

        mHomeText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mNearText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mShoppingText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mOrderText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mMianText.setTextColor(getResources().getColor(R.color.app_color_qian));

        mHomeImage.setSelected(false);
        mNearImage.setSelected(false);
        mShoppingImage.setSelected(false);
        mOrderImage.setSelected(false);
        mMianImage.setSelected(false);

        switch (v.getId()) {
            case R.id.home_linear:
                if (!mList.get(0).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(0));
                }
                transaction.show(mList.get(0));
                mHomeText.setTextColor(getResources().getColor(R.color.app_color));
                mHomeImage.setSelected(true);
                break;
            case R.id.near_linear:
                if (!mList.get(1).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(1));
                }
                transaction.show(mList.get(1));
                mNearText.setTextColor(getResources().getColor(R.color.app_color));
                mNearImage.setSelected(true);
                break;
            case R.id.threed_button:
                if (TextUtils.isEmpty(PreferenceUtils.getPrefString("account_type", "")) || TextUtils.equals("1", PreferenceUtils.getPrefString("account_type", ""))) {
                    if (!mList.get(2).isAdded()) {
                        transaction.add(R.id.framelayout, mList.get(2));
                    }
                    transaction.show(mList.get(2));
                    mShoppingText.setTextColor(getResources().getColor(R.color.app_color));
                    mShoppingImage.setSelected(true);
                    mShoppingLinear.setVisibility(View.VISIBLE);
                    mOrderLinear.setVisibility(View.GONE);

                } else {

                    if (!mList.get(3).isAdded()) {
                        transaction.add(R.id.framelayout, mList.get(3));
                    }
                    transaction.show(mList.get(3));
                    mOrderText.setTextColor(getResources().getColor(R.color.app_color));
                    mOrderImage.setSelected(true);
                    mShoppingLinear.setVisibility(View.GONE);
                    mOrderLinear.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.mian_linear:

                if (!mList.get(4).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(4));
                }
                transaction.show(mList.get(4));
                mMianText.setTextColor(getResources().getColor(R.color.app_color));
                mMianImage.setSelected(true);
                break;
        }
        transaction.commit();
    }

    /**
     * @param position 指定的切换到的Fragment
     */
    public void onCrureectToFragment(int position) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.hide(mList.get(0));
        transaction.hide(mList.get(1));
        transaction.hide(mList.get(2));
        transaction.hide(mList.get(3));
        transaction.hide(mList.get(4));

        mHomeText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mNearText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mShoppingText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mOrderText.setTextColor(getResources().getColor(R.color.app_color_qian));
        mMianText.setTextColor(getResources().getColor(R.color.app_color_qian));


        mHomeImage.setSelected(false);
        mNearImage.setSelected(false);
        mShoppingImage.setSelected(false);
        mOrderImage.setSelected(false);
        mMianImage.setSelected(false);

        switch (position) {
            case 0:
                if (!mList.get(0).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(0));
                }
                transaction.show(mList.get(0));
                mHomeText.setTextColor(getResources().getColor(R.color.app_color));
                mHomeImage.setSelected(true);
                break;
            case 1:
                if (!mList.get(1).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(1));
                }
                transaction.show(mList.get(1));
                mNearText.setTextColor(getResources().getColor(R.color.app_color));
                mNearImage.setSelected(true);
                break;
            case 2:
                if (TextUtils.isEmpty(PreferenceUtils.getPrefString("account_type", "")) || TextUtils.equals("1", PreferenceUtils.getPrefString("account_type", ""))) {
                    if (!mList.get(2).isAdded()) {
                        transaction.add(R.id.framelayout, mList.get(2));
                    }
                    transaction.show(mList.get(2));
                    mShoppingText.setTextColor(getResources().getColor(R.color.app_color));
                    mShoppingImage.setSelected(true);
                    mShoppingLinear.setVisibility(View.VISIBLE);
                    mOrderLinear.setVisibility(View.GONE);

                } else {

                    if (!mList.get(3).isAdded()) {
                        transaction.add(R.id.framelayout, mList.get(3));
                    }
                    transaction.show(mList.get(3));
                    mOrderText.setTextColor(getResources().getColor(R.color.app_color));
                    mOrderImage.setSelected(true);
                    mShoppingLinear.setVisibility(View.GONE);
                    mOrderLinear.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                if (!mList.get(4).isAdded()) {
                    transaction.add(R.id.framelayout, mList.get(4));
                }
                transaction.show(mList.get(4));
                mMianText.setTextColor(getResources().getColor(R.color.app_color));
                mMianImage.setSelected(true);
                break;
        }
        transaction.commit();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        RefWatcher refWatcher = ExitApplication.getRefWatcher(MianButtonActivity.this);
        refWatcher.watch(this);
    }

    private void httpGetUserInfo(String url) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败

                            break;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            UserInfoModel.setUser_info(user_info);
                            PreferenceUtils.setPrefString("address", user_info.getAddress());
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }


        });
    }
}
